[ORG 0x7c00]

[SECTION .text]
[BITS 16]
global _start

_start:
	call get_mem_map
	mov edi,0x500
	mov ecx,1
	mov bl,1
	call read_disk
	mov ax,test_str
	call print
	jmp 0x500

; =============================
; 获取内存布局
ARD_ENTRY equ 0x8000
ARD_COUNT equ 0x7900

get_mem_map:
	mov dword [ARD_COUNT],0
	mov ax,0
	mov es,ax
	xor ebx,ebx
	mov di,ARD_ENTRY

get_mem_map_loop:
	mov eax,0xe820
	mov ecx,20
	mov edx,0x534d4150
	int 0x15
	jc get_mem_map_fail
	add di,20
	inc dword [ARD_COUNT]
	cmp ebx,0
	jne get_mem_map_loop
	ret

get_mem_map_fail:
	mov ax,err_e820
	call print
	hlt
	

read_disk:
    mov dx,0x1f2
    mov al,bl
    out dx,al

    inc dx ; 0x1f3
    mov al,cl
    out dx,al

    inc dx ; 0x1f4
	shr ecx,8
    mov al,cl
    out dx,al
    
    inc dx ; 0x1f5
	shr ecx,8
	mov al,cl
    out dx,al

    inc dx ; 0x1f6
	shr ecx,8
	and cl,0b1111

    mov al,0b1110_0000
	or al,cl
    out dx,al

    inc dx ; 0x1f7
    mov al,0x20
    out dx,al

	xor ecx,ecx
    mov cl,bl

    .read:
        push cx
        call .waits
        call .reads
        pop cx
        loop .read
	ret
		.waits:
			mov dx,0x1f7
			.check:
				in al,dx
				jmp $+2
				jmp $+2
				jmp $+2
				and al,0b1000_1000
				cmp al,0b0000_1000
				jnz .check
			ret
		.reads:
			mov dx,0x1f0
			mov cx,256
			.readw:
				in ax,dx
				jmp $+2
				jmp $+2
				jmp $+2
				mov [edi],ax
				add edi,2
				loop .readw
			ret

disk_error:
	mov si,err_str
	call print
	hlt


print:
	mov si,ax
	mov ah,0x0e
	mov bl,0

	.next_char:
		mov al,[si]
		cmp al,0
		je .done
		int 0x10
		inc si
		jmp .next_char
	.done:
		ret

err_str: db "read disk err",0
test_str: db "this is test str",0
err_e820: db "E820 error!",0

times 510-($-$$) db 0
db 0x55,0xaa
